﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace HostOptions
{
    public class BackgroudService : IHostedService
    {
        private Timer _timer;  
        IServiceProvider serviceProvider;

        public BackgroudService(IServiceProvider serviceProvider)
        {
            this.serviceProvider = serviceProvider;
        }


        public Task StartAsync(CancellationToken cancellationToken)
        {
            _timer = new Timer(work, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));  
            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _timer.Dispose();
            return Task.CompletedTask;
        }

        private void work(object state)
        {
            using (var serviceScope = serviceProvider.CreateScope()) //为services.AddScoped申明的对象创建范围，此范围内多次调用GetService会返回同一对象，超出此范围会返回新对象
            {
                var ioc = serviceScope.ServiceProvider.GetService<IocClass>();
                //ioc = serviceScope.ServiceProvider.GetService<IocClass>();
                ioc.TestMothed();
            }
        }
    }
}
